
package org.apache.solr.servlet;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * A Simple redirection servlet to help us deprecate old UI elements
 */
public class RedirectServlet extends HttpServlet {

    static final String CONTEXT_KEY = "${context}";

    String destination;
    int code = HttpServletResponse.SC_MOVED_PERMANENTLY;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        destination = config.getInitParameter("destination");
        System.out.println("\nCONTEXT_KEY="+CONTEXT_KEY+"\ndestination="+destination+"\ncode="+code);
        if (destination == null) {
            throw new ServletException("RedirectServlet missing destination configuration");
        }
        if ("false".equals(config.getInitParameter("permanent"))) {
            code = HttpServletResponse.SC_MOVED_TEMPORARILY;
        }

        // Replace the context key
        if (destination.startsWith(CONTEXT_KEY)) {
            destination = config.getServletContext().getContextPath() + destination.substring(CONTEXT_KEY.length());
        }
    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        res.setStatus(code);
        res.setHeader("Location", destination);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        doGet(req, res);
    }
}
